﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentScheduler;
using Ttifa.Log;

namespace Ttifa.JobScheduler
{
    public class FluentSchedulerDemo
    {
        public Registry Registry()
        {
            var registry = new Registry();
            //每日13点执行
            registry.Schedule(() => LogFactory.GetLogger().Info("每日任务")).ToRunEvery(1).Days().At(14, 35);
            //立即执行一个在每月的第一个星期一 3:00 的计划任务
            //registry.Schedule<DailyJob>().ToRunNow().AndEvery(1).Months().OnTheFirst(DayOfWeek.Monday).At(3, 0);

            // 在同一个计划中执行两个（多个）任务
            registry.Schedule<MyJob>().AndThen<DailyJob>().ToRunNow().AndEvery(1).Minutes();

            return registry;
        }

        public void Start()
        {
            JobManager.Initialize(Registry());
            JobManager.JobException += (info) => LogFactory.GetLogger().Error("An error just happened with a scheduled job: " + info.Exception);
        }

        public void Stop()
        {
            JobManager.StopAndBlock();
        }
    }

    public class DailyJob : IJob
    {
        private readonly object _lock = new object();
        private bool _shuttingDown;
        public void Execute()
        {
            lock (_lock)
            {
                if (_shuttingDown)
                    return;

                // ToDo
                LogFactory.GetLogger().Info("dailyjob");
            }
        }

        public void Stop(bool immediate)
        {
            // Locking here will wait for the lock in Execute to be released until this code can continue.
            lock (_lock)
            {
                _shuttingDown = true;
            }
        }
    }

    public class MyJob : IJob
    {
        public void Execute()
        {
            LogFactory.GetLogger().Info("myjob");
        }
    }
}
